package com.trendit.classicpos.util;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;

import java.nio.ByteBuffer;

public class BitmapUtils {

    /**
     * RGB 565图片颜色数组封装成图片
     *
     * @param data   颜色数组
     * @param height 高度
     * @param width  宽度
     * @return
     */
    public static Bitmap getOriginalBitmap(byte[] data, int width, int height, Bitmap.Config config) {
        Bitmap bitmap = Bitmap.createBitmap(width, height, config);
        ByteBuffer buffer = ByteBuffer.wrap(data);
        bitmap.copyPixelsFromBuffer(buffer);
        return bitmap;
    }



    /**
     * 按比例缩放图片
     *
     * @param origin 原图
     * @param ratio  比例
     * @return 新的bitmap
     */
    public static Bitmap scaleBitmap(Bitmap origin, float ratio) {
        if (origin == null) {
            return null;
        }
        int width = origin.getWidth();
        int height = origin.getHeight();
        Matrix matrix = new Matrix();
        matrix.preScale(ratio, ratio);
        Bitmap newBM = Bitmap.createBitmap(origin, 0, 0, width, height, matrix, false);
        if (newBM.equals(origin)) {
            return newBM;
        }
        origin.recycle();
        return newBM;
    }

    /**
     * 构建单色图bitmap
     */
    public static Bitmap buildMonoChromeBitmap(int width, int height, byte[] picBuf) {
        int xPosition;
        int yPosition;
        int i;
        int j;
        int bufLen = picBuf.length;

        Bitmap targetBmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        Canvas targetCanvas = new Canvas(targetBmp);
        targetCanvas.drawColor(Color.WHITE);
        Paint paint = new Paint();
        paint.setColor(Color.BLACK);

        for (i = 0; i < bufLen; i++) {
            byte[] binary = ByteUtils.byteToBinary(picBuf[i]);
            for (j = 0; j < 8; j++) {
                if (binary[j] == 1) {
                    int point = i * 8 + j;
                    xPosition = point % width;
                    yPosition = point / width;
                    targetCanvas.drawPoint(xPosition, yPosition, paint);
                }
            }
        }
        return targetBmp;
    }
}
